package com.laolang.pluto.framework.config.security.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.laolang.pluto.common.util.ServletKit;
import com.laolang.pluto.framework.config.security.pojo.LoginUser;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author laolang
 * @date 2021-08-07 05:37
 */
@RequiredArgsConstructor
@Service("ss")
public class PermissionService {

    private static final String ALL_PERMISSION = "*:*:*";

    private static final String SUPER_ADMIN = "admin";

    private static final String ROLE_DELIMETER = ",";

    private static final String PERMISSION_DELIMETER = ",";

    private final TokenService tokenService;

    public boolean hasPermi(String permission) {
        if (StrUtil.isBlank(permission)) {
            return false;
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletKit.getRequest());
        if (null == loginUser || CollUtil.isEmpty(loginUser.getPermissionList())) {
            return false;
        }
        return hasPermissions(loginUser.getPermissionList(), permission);
    }

    // TODO 正则匹配
    private boolean hasPermissions(Set<String> permissionList, String permission) {
        return permissionList.contains(ALL_PERMISSION) || permissionList.contains(StringUtils.trim(permission));
    }
}
